package com.batchbrake.queue;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

import com.batchbrake.main.EFile;
import com.batchbrake.main.SrtUtils;
import com.batchbrake.progress.ProgressEvent;

public class QueueBuilder extends Observable implements Runnable {
	public static final String[] inputFormats = new String[] { "avi", "mpg", "wmv", "mpeg" };
	public static final String[] outputFormats = new String[] { "mp4", "m4v" };

	private List<EFile> files = new ArrayList<EFile>();
	private List<EFile> outputFolders = new ArrayList<EFile>();
	private List<String> formats = new ArrayList<String>();
	private List<QueueEntity> queue = null;
	
	
	public void addToQueue(EFile file, EFile outputFolder, String outputFormat) {
		if( file.isDirectory() ) {
			EFile files[] = file.listEFiles();
			String ext = null;
			
			for( int i = 0; i < files.length; i++ ) {
				if( (ext = files[i].getExtension()) != null ) {
					for( int k = 0; k < inputFormats.length; k++ ) {
						if( ext.equals(inputFormats[k]) ) {
							this.files.add(files[i]);
							this.outputFolders.add(outputFolder);
							if( outputFormat.startsWith(".") ) {
								this.formats.add(outputFormat);
							} else {
								this.formats.add("." + outputFormat);
							}
						}
					}
				}
			}
		} else {
			files.add(file);
			outputFolders.add(outputFolder);
			formats.add(outputFormat);
		}
	}
	
	
	
	public List<QueueEntity> getQueue() {
		return queue;
	}
	public void clearAll() {
		queue.clear();
		files.clear();
		outputFolders.clear();
		formats.clear();
	}
	
	


	@Override
	public void run() {
		ProgressEvent e = new ProgressEvent();
		queue = new ArrayList<QueueEntity>();	
		e.setMin(0);
		e.setMax(files.size());
		e.setValue(0);
		this.setChanged();
		this.notifyObservers(e);

		for( int i = 0; i < files.size(); i++ ) {
			QueueEntity entity = new QueueEntity();
			entity.setSubtitles(SrtUtils.searchSrtFiles(files.get(i)));
			entity.setInput(files.get(i));
			entity.setOutput(new EFile(outputFolders.get(i) + File.separator + files.get(i).getBaseName() + formats.get(i)));

			List<String> langs = new ArrayList<String>();
			for( int m = 0; m < entity.getSubtitles().size(); m++ ) {
				try {
					langs.add(SrtUtils.guessLangOfSrtFile(entity.getSubtitles().get(m)));
				} catch (IOException ex) {
					ex.printStackTrace();
					langs.add("unknown");
				}
			}

			List<String> encodings = new ArrayList<String>();
			for( int m = 0; m < langs.size(); m++ ) {
				encodings.add(langs.get(m).toString().equals("fra") ? "ISO-8859-1" : "UTF8");
			}

			entity.setLangs(langs);
			entity.setEncodings(encodings);

			queue.add(entity);
			e.setValue(i+1);
			this.setChanged();
			this.notifyObservers(e);
		}
	}
}